﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Mvc;
using Kevin.Comm.Utility;
using Kevin.Comm.Web;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Core.Components.Sales;
using Kevin.Shop.Business.Core.Member;
using Kevin.Shop.Business.SalesManagement.Components.Order;
using Kevin.Shop.Business.SalesManagement.Enumerations;
using Kevin.Shop.Business.Service.Entity.Helper;
using Kevin.Shop.Business.Shopping.Components;
using RiderShop.Mobile.Common.Helper;
using RiderShop.Mobile.Modle;
using RiderShop.Mobile.Modle.MyAccount;
using RiderShop.Mobile.Modle.Purchase;
using RiderShop.Mobile.Common.Component;
using Kevin.Shop.Business.Core.Enumerations;
using System.Web.Security;
using RiderShop.Mobile.ServiceEntity.MyAccount;
using Kevin.Shop.Business.Core.Components;
using RiderShop.Web.YinxinPay;
using Kevin.Comm.Logger;

namespace RiderShop.Mobile.Controllers.Purchase
{
    public partial class PurchaseController : ThemeController
    {
        public ActionResult ShoppingCart(string act, string pId, string qty)
        {
            var model = new ShippingCartModel();
            model.UpdataShippingCart(act, pId, qty);
            //return View(model);
            //model.CartInfo.ProductList = new List<ShoppingCartItemInfo>()
            //{
            //    new ShoppingCartItemInfo(){
            //    ProductId = "10090008008",
            //    ProductType = Kevin.Shop.Business.Products.Enumerations.ProductInfoType.Product,
            //    Quantity = 2,
            //    UnitPrice = 12.32M,
            //    Title = "Dexter Yao",
            //    LimitQuantity = 3,
            //     ShippingCharge = 1,

            //    }
            //};
            //return View(WebClientContext.Current.SiteTheme, "Purchase", "ShoppingCart", "_MobileLayout", model);

            return View(WebClientContext.Current.SiteTheme, "Purchase", "ShoppingCart", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        public JsonResult PreCheckProduct()
        {
            var model = new ShippingCartModel();
            var result = model.PreCheckProduct();
            return Json(new ServiceResponser(result == string.Empty, result));
        }

        [Authorize]
        public ActionResult CheckOut(string behaviour = "isNoGreetingOrder")
        {
            var model = new CheckOutModel();
            //return View(model);
            //本地礼品订单 || 外地礼品订单
            if (behaviour == "isGreetingOrder" || behaviour == "isGreetingOrderForNonlocal")
            {
                var productList = model.CartInfo.CommonProductListNoCOM;
                if (productList.Any(p => p.GiftShippingType != 1))
                {
                    behaviour = "isNoGreetingOrder";
                }
            }

            model.Behaviour = behaviour;
            return View(WebClientContext.Current.SiteTheme, "Purchase", "CheckOut", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        [Authorize]
        public ActionResult SubmitOrder()
        {
            string strJson = WebClientContext.ReadJsonStringFromRequestBody(Request.InputStream);
            string str = WebHelper.UrlDecode(strJson).Replace("\r\n", @" ");
            var order = Serializer.ConvertJsonToObject<OrderBasicInfo>(str, true);
            order.OrderSource = OrderSourceType.Mobile;
            //送礼订单
            if (order.IsGreetingOrder)
            {
                order.OrderType = 6;
            }
            var model = new CheckOutModel();
            var result = model.SubmitOrder(order);
            if (result.Status)
            {
                ShoppingCartHelper.ProcessShoppingCart("clear", string.Empty, string.Empty);
            }
            else
            {
                return Json(result);
            }
            return Json(result);
        }

        [Authorize]
        public ActionResult OrderCompleted()
        {
            var tag = Request.QueryString["par"];
            return View(WebClientContext.Current.SiteTheme, "Purchase", "OrderCompleted", WebClientContext.Current.CacheKeyDefaultMasterPage, new OrderCompletedModel(tag));
        }

        [Authorize]
        public JsonResult OrderBalanceCompute(int shiptype, int shippingId, string promotionCode, int point = 0)
        {
            var model = new CheckOutModel();
            var result = model.OrderBalanceCompute(shiptype, shippingId, promotionCode, point);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        [HttpGet]
        public ActionResult YinxinPay(string orderNumber)
        {
            if (string.IsNullOrEmpty(orderNumber))
            {
                return RedirectToAction("OrderList", "MyAccount", new { orderStatus = 1 });
            }
            PaymentModel model = new PaymentModel();
            model.OrderBasicInfo = model.GetOrderBasicInfoByOrderId(orderNumber);

            if (model.OrderBasicInfo == null)
            {
                return RedirectToAction("OrderList", "MyAccount", new { orderStatus = 1 });
            }

            if (model.OrderBasicInfo.OrderStatus != OrderStatus.待支付)
            {
                return RedirectToAction("OrderDetail", "MyAccount", new { orderNumber = model.OrderBasicInfo.OrderNumber });
            }

            return View(WebClientContext.Current.SiteTheme, "Purchase", "YinxinPay", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        [HttpPost]
        public JsonResult YinxinPay(string orderNumber, string cardNumber, string password, string cardType)
        {
            if (!string.IsNullOrEmpty(orderNumber) && !string.IsNullOrWhiteSpace(cardNumber) && !string.IsNullOrWhiteSpace(password))
            {
                orderNumber = orderNumber.Trim();
                cardNumber = cardNumber.Trim();
                PaymentModel model = new PaymentModel();
                model.OrderBasicInfo = model.GetOrderBasicInfoByOrderId(orderNumber);

                if (model.OrderBasicInfo == null)
                {
                    return Json("0");
                }

                if (model.OrderBasicInfo.OrderStatus != OrderStatus.待支付)
                {
                    return Json("0");
                }

                if (cardType == "xx" && !cardNumber.StartsWith(ConfigurationManager.AppSettings["XianxiangCardPrefix"]))
                {
                    return Json("鲜享卡卡号不正确");
                }


                cardNumber = cardNumber.Trim();
                password = password.Trim();
                string gatwayNumber = YinxinPayHelper.CreateGatewayOrderNumber(model.OrderBasicInfo.OrderNumber);

                decimal orderPayAmount = model.OrderBasicInfo.OrderPayAmount;

                try
                {
                    Tracer.TraceLog("card: " + cardNumber + "pay order: " + orderNumber + " yinxin order: " + gatwayNumber, "Yin Xin Pay", "YinxinPayment", true);

                    //鲜享卡支付立减折扣
                    if (cardType == "xx" && cardNumber.StartsWith(ConfigurationManager.AppSettings["XianxiangCardPrefix"]))
                    {
                        decimal discount = model.GetOrderPaymentDiscount(model.CheckYinXinCardType(cardNumber));
                        if (discount > 0)
                        {
                            orderPayAmount = orderPayAmount - discount;
                            Tracer.TraceLog("pay discount:" + discount, "Yin Xin Pay", "YinxinPayment", true);
                        }
                    }

                    var result = YinxinPayHelper.CommitOrder(gatwayNumber, cardNumber, password, orderPayAmount);
                    if (string.IsNullOrEmpty(result))
                    {
                        Tracer.TraceLog("pay successfully", "Yin Xin Pay", "YinxinPayment", true);
                        model.CreateOrderPaymentInfo(model.OrderBasicInfo.OrderNumber, gatwayNumber, orderPayAmount, cardNumber, (int)model.CheckYinXinCardType(cardNumber));
                        return Json("1");
                    }
                    else
                    {
                        Tracer.TraceLog("pay result: " + result, "Yin Xin Pay", "YinxinPayment", true);
                        return Json(result);
                    }
                }
                catch (Exception e)
                {
                    Tracer.TraceLog("pay exception: " + e.Message, "Yin Xin Pay", "YinxinPayment", true);

                    try
                    {
                        var result = YinxinPayHelper.QueryOrder(gatwayNumber);
                        if (string.IsNullOrEmpty(result))
                        {
                            Tracer.TraceLog("query & pay successfully", "Yin Xin Pay", "YinxinPayment", true);
                            model.CreateOrderPaymentInfo(model.OrderBasicInfo.OrderNumber, gatwayNumber, orderPayAmount, cardNumber, (int)model.CheckYinXinCardType(cardNumber));
                            return Json("0");
                        }
                        else
                        {
                            Tracer.TraceLog("query result: " + result, "Yin Xin Pay", "YinxinPayment", true);
                            return Json(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        Tracer.TraceLog("query exception: " + ex.Message, "Yin Xin Pay", "YinxinPayment", true);
                        return Json("服务器异常，请刷新页面重试！");
                    }
                }
            }
            return Json("0");
        }

        [HttpPost]
        public JsonResult YinxinBalance(string cardNumber, string password)
        {
            if (!string.IsNullOrWhiteSpace(cardNumber) && !string.IsNullOrWhiteSpace(password))
            {
                cardNumber = cardNumber.Trim();
                try
                {
                    string balance = YinxinPayHelper.QueryBalance(cardNumber, password);

                    return Json(balance);
                }
                catch (Exception ex)
                {
                    Tracer.TraceLog("query exception: " + ex.Message, "Yin Xin Pay", "YinxinPayment", true);
                    return Json("服务器异常，请刷新页面重试！");
                }
            }
            else
            {
                return Json("");
            }

        }

        [Authorize]
        [HttpGet]
        public ActionResult YinxinBalance()
        {
            return View(WebClientContext.Current.SiteTheme, "Purchase", "YinxinBalance", WebClientContext.Current.CacheKeyDefaultMasterPage, null);
        }

        [HttpPost]
        public JsonResult YinxinDiscount(string orderNumber, string cardNumber)
        {
            if (!string.IsNullOrEmpty(orderNumber) && !string.IsNullOrWhiteSpace(cardNumber))
            {
                orderNumber = orderNumber.Trim();
                cardNumber = cardNumber.Trim();
                PaymentModel model = new PaymentModel();
                model.OrderBasicInfo = model.GetOrderBasicInfoByOrderId(orderNumber);

                if (model.OrderBasicInfo == null)
                {
                    return Json("");
                }

                if (model.OrderBasicInfo.OrderStatus != OrderStatus.待支付)
                {
                    return Json("");
                }

                decimal orderPayAmount = model.OrderBasicInfo.OrderPayAmount;

                //鲜享卡支付立减折扣

                decimal discount = model.GetOrderPaymentDiscount(model.CheckYinXinCardType(cardNumber));

                orderPayAmount = orderPayAmount - discount;
                return Json(new { discount = discount, orderPayAmount = orderPayAmount });


            }
            else
            {
                return Json("");
            }

        }


        public ActionResult QuicklyOrder(string prdId, int qty = 1)
        {
            string openId = string.Empty;

            if (Request.Form["openId"] != null)
            {
                openId = Request.Form["openId"];
                openId = openId.Replace("weixin_", string.Empty);
            }
            else
            {
                if (!string.IsNullOrEmpty(WebClientContext.Current.OpenId))
                {
                    openId = WebClientContext.Current.OpenId;
                    if (string.IsNullOrEmpty(Request.QueryString["signature"]) || Request.QueryString["signature"] != GetSha1(openId).ToString().ToLower())
                    {
                        return new EmptyResult();
                    }
                }
                else
                {
                    return new EmptyResult();
                }
            }

            //使用openId登陆
            var user = MyAccountModel.GetUserInfoByThirdId("weixing_" + openId);
            if (user.UserId <= 0)
            {
                //request info
                string realName = Request.Form["realName"];
                string headUrl = Request.Form["headUrl"];
                string sex = Request.Form["sex"];
                //string prd = Request.Form["prd"];
                user.ThirdUserId = "weixing_" + openId;
                user.RealName = realName;
                user.IsMale = sex == 1.ToString();
                user.HeadImgUrl = headUrl;
                user.UserName = "weixing_" + DateTime.Now.ToString("yyMMddhhmmssfff");
                user.Email = openId + "@weixin.com";
                user.UserType = UserType.RegisteredUser;
                user.Password = "000000";

                string url = SiteUrl.FormatUrl("Common_CreateOrUpdateUser");
                ServiceResponser Result = RestfulHelper.Update(url, user);
                user = MyAccountModel.GetUserInfoByThirdId("weixing_" + openId);
            }
            if (!WebClientContext.Current.IsAuthenticated || WebClientContext.Current.UserName != user.UserName)
            {
                //login
                WebClientContext.Current.OpenId = openId;
                FormsAuthentication.SetAuthCookie(user.UserName, true);
                WebClientContext.Current.GetCurrentUser(false);
                string signature = GetSha1(openId).ToString().ToLower();
                return Redirect(Request.Url.ToString() + "?prd=" + Request.Form["prd"] + "&signature=" + signature);
            }

            //获取用户是否购买过活动商品
            var orderNumber = KevinCookieManager.Get("ValentineUserOrder");
            if (string.IsNullOrEmpty(orderNumber))
            {
                OrderQueryBasicInfo query = new OrderQueryBasicInfo();

                query.OrderType = 1;
                query.OrderBeginDate = DateTime.Now.AddMonths(-1).Date;
                query.OrderEndDate = DateTime.Now.Date.AddDays(1).Date;
                query.InUser = WebClientContext.Current.UserId;
                query.CurrentUserId = WebClientContext.Current.UserId;
                query.PageIndex = 0;
                query.PageSize = 10;
                query.Keywords = "10430002005";
                DbQueryResult<List<OrderBasicInfo>> orderList = RestfulHelper.Query<OrderBasicInfo>(SiteUrl.FormatUrl("SalesManagement_GetUserRecentlyOrder"), query);
                if (orderList.Data != null && orderList.Data.Count > 0)
                {
                    orderNumber = orderList.Data[0].OrderNumber;
                }
                //  ''foreach (var order in orderList.Data)
            }
            var model = new CheckOutModel();
            ShoppingCartHelper.ProcessShoppingCart("clear", string.Empty, string.Empty);
            OrderBasicInfo order;
            if (!string.IsNullOrEmpty(orderNumber) && user.UserId > 0)
            {
                order = OrderModel.GetOrderDetailInfo(orderNumber);
                model.CurrentOrder = order;
                if (order.OrderStatus == OrderStatus.待支付)
                {
                    return View(model);
                }
                else
                {
                    //如果订单中的商品是'情人节活动商品'跳转到排名界面
                    if (order.ProductList.Any(p => "10430002005".Contains(p.ProductId)))
                    {
                        bool activitySwitch = false;
                        bool.TryParse(ConfigurationManager.AppSettings["ActivitySwitch"], out activitySwitch);
                        if (activitySwitch)
                        {
                            if (!string.IsNullOrEmpty(order.UserMemo))
                            {
                                order.UserMemo = order.UserMemo.Trim().Replace("ActivityPrd-", "");//用户挑选的商品
                            }
                            else
                            {
                                order.UserMemo = "0";
                            }
                            //组织要传回去的参数portal name & signature
                            string portalName = ConfigurationManager.AppSettings["WeixinPortalName"];
                            string activityId = ConfigurationManager.AppSettings["ActivityId"];
                            string weixin_openId = WebClientContext.Current.CurrentUser.ThirdUserId.ToLower().Replace("weixing_", "").Replace("weixin_", "");
                            string signature = GetSha1(weixin_openId).ToString().ToLower();

                            return Redirect("http://m.rongji365.com/weixinportal/Activity/QingRenJieRank?payComplete=finished&id="
                                + activityId + "&portal=" + portalName + "&pid=" + order.UserMemo + "&signature=" + signature + "&address=" + order.ReceiveAddress);
                        }
                    }
                }
            }

            //Create Order
            order = new OrderBasicInfo();
            order.CustomerUserId = user.UserId;
            order.CurrentUserId = user.UserId;
            order.ShippingId = -999;
            order.ArrivePay = 0;

            order.ProductList = new ObservableCollection<OrderProductInfo>();
            var prodct = new OrderProductInfo();
            prodct.ProductId = "10430002005";
            prodct.Quantity = 1;
            order.ProductList.Add(prodct);

            order.UserMemo = "ActivityPrd-" + (Request.Form["prd"] == null ? Request.QueryString["prd"] : Request.Form["prd"]);

            model.SubmitOrder(order);

            if (model.OrderResult != null && !string.IsNullOrEmpty(model.OrderResult.Tag))
            {
                var str = model.OrderResult.Tag.Split(',');
                orderNumber = str.Length == 3 ? str[0] : string.Empty;
                model.CurrentOrder = OrderModel.GetOrderDetailInfo(orderNumber);
                KevinCookieManager.Set("ValentineUserOrder", orderNumber);
            }
            return View(model);
        }

        [Authorize]
        public JsonResult UpdateOrderShipping(int shippingId, string orderNumber, string tel, string name)
        {
            if (string.IsNullOrEmpty(orderNumber) && string.IsNullOrEmpty(tel) && string.IsNullOrEmpty(name))
            {
                return Json("请输入完整的用户信息", JsonRequestBehavior.AllowGet);
            }
            //name = URLEncoder.encode(name, "utf-8");
            /**
            ShippingId	RegionId	UserId	ShipTo	Address
            1672	2760	-999	民生家乐科技路店	太白南路263号
            1673	2760	-999	民生家乐丈八路店	丈八路与科技三路交汇处玫瑰公馆2号
            1674	2759	-999	民生家乐文景路店	西安市未央区文景路2号
             * **/
            var shippModel = new CheckOutModel();
            var shippings = shippModel.GetUserShippingAddress(999999999, shippingId);//-999是临时地址
            if (shippings.Count > 0)
            {
                var orderModel = new PaymentModel();
                var orderInfo = orderModel.GetOrderBasicInfoByOrderId(orderNumber);
                orderInfo.ShippingId = shippingId;
                orderInfo.ReceivePhone = name + ": " + tel;
                orderInfo.CustomerUserName = "民生家乐活动";
                orderInfo.RegionId = shippings[0].RegionId;
                orderInfo.ReceiveAddress = shippings[0].ShipTo + " " + shippings[0].Address;
                orderInfo.ReceiveCellPhone = shippings[0].CellPhone;

                //10120002006
                var model = new GreetingOrderModel();
                var response = model.AddGreetingAddress(orderInfo);
                return Json(response, JsonRequestBehavior.AllowGet);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);

        }


        [Authorize]
        [HttpGet]
        public ActionResult ZiTiDianMap()
        {
            //得到系统的所有自提点
            List<UserShipingAddressExtend> defaultPickAddressList = MyAccountModel.GetShippingAddress(100, -1) ?? new List<UserShipingAddressExtend>();

            return View(WebClientContext.Current.SiteTheme, "Purchase", "ZiTiDianMap", WebClientContext.Current.CacheKeyDefaultMasterPage, defaultPickAddressList);
        }
    }
}